package cn.bupt.adt.controller;


import cn.bupt.adt.constant.Constants;
import cn.bupt.adt.entity.autogenerate.AdminUser;
import cn.bupt.adt.entity.autogenerate.AdminUserExample;
import cn.bupt.adt.entity.autogenerate.Attached;
import cn.bupt.adt.entity.autogenerate.AttachedExample;
import cn.bupt.adt.model.AdminUserModel;
import cn.bupt.adt.service.IAdminUserService;
import cn.bupt.adt.service.IAttachedService;
import cn.bupt.adt.service.LoginService;
import cn.bupt.adt.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("/public")
public class LoginController {

    @Autowired
    LoginService loginServie;
    @Autowired
    IAdminUserService adminUserService;

    @Autowired
    IAttachedService attachedService;

    @RequestMapping("/login")
    public ModelAndView login(AdminUser user, HttpServletRequest request) {
        ModelAndView modelAndView;
        if ("GET".equals(request.getMethod()) || null == user) {
            modelAndView = new ModelAndView(Constants.PUBLIC_LOGIN);
        } else {
            AdminUser adminUser = loginServie.getUserByName(user.getName());
            if (adminUser == null) {
                request.setAttribute("errorInfo", "用户不存在,请输入正确的账号");
                modelAndView = new ModelAndView(Constants.PUBLIC_LOGIN);
            } else {
                if (!adminUser.getPasswd().equals(MD5Util.MD5(user.getPasswd()))) {
                    request.setAttribute("errorInfo", "密码错误");
                    modelAndView = new ModelAndView(Constants.PUBLIC_LOGIN);
                } else {
                    HttpSession session = request.getSession();
                    if (session.getAttribute(Constants.ADMIN_USER) == null) {
                        session.setAttribute(Constants.ADMIN_USER, adminUser);
                        session.setAttribute(Constants.LAST_LOGIN_IN_IP, request.getRemoteAddr());
                        loginServie.saveLastLoginInTme(adminUser);
                    }
                    modelAndView = new ModelAndView(Constants.PUBLIC_HOME);
                    if (adminUser.getLastLoginInTime() != null)
                        modelAndView.addObject("name", adminUser.getName());
                    modelAndView.addObject("lastLoginTime", adminUser.getLastLoginInTime());
                    modelAndView.addObject("id", adminUser.getId());
                }
            }
        }
        return modelAndView;
    }

    @RequestMapping("/blank")
    public ModelAndView blank(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView(Constants.BLANK_PAGE);
        AdminUser user = (AdminUser) request.getSession().getAttribute(Constants.ADMIN_USER);
/*		modelAndView.addObject("doctorNum", adminUserService.getdoctorNum());
		modelAndView.addObject("onGingOrderNum", adminUserService.getonGingOrderNum());
		modelAndView.addObject("allOrderNum", adminUserService.getallOrderNum());*/
        modelAndView.addObject("adminUserId", user.getId());
        return modelAndView;
    }

    /**
     * 修改密码界面，跳转
     *
     * @param
     * @return
     */
    @RequestMapping("/jumpSecretEdit/{id}")
    public ModelAndView jumpSecretEdit(@PathVariable(value = "id") int id) {
        ModelAndView modelAndView = new ModelAndView("public/update");
        AdminUser adminUser = loginServie.getUserById(id);
        modelAndView.addObject("adminUser", adminUser);
        return modelAndView;
    }

    /**
     * 保存新密码
     */
    @RequestMapping("/updatePasswd")
    public ModelAndView saveSecretEdit(AdminUserModel adminUser, HttpServletRequest request)
            throws IllegalStateException, IOException {
        ModelAndView mv = new ModelAndView("pubic/update");
        AdminUserExample userEx = new AdminUserExample();
        cn.bupt.adt.entity.autogenerate.AdminUserExample.Criteria criteria = userEx.createCriteria();
        criteria.andPasswdEqualTo(adminUser.getPasswd());
        System.out.println("=" + adminUser.getPasswd());
        AdminUser user = loginServie.getUserById(adminUser.getId());
        if (MD5Util.MD5(adminUser.getPasswd()).equals(user.getPasswd())) {
            //输入原密码正确
            Boolean flag = adminUserService.updateSecret(adminUser);
            if (flag) {
                request.setAttribute("resultMsg", "修改成功");
                mv = new ModelAndView("forward:/public/adminUserDetail/" + adminUser.getId());
            } else {
                request.setAttribute("resultMsg", "修改失败请重试");
                mv = new ModelAndView("forward:/public/jumpSecretEdit/" + adminUser.getId());
            }

        } else {
            request.setAttribute("resultMsg", "原密码输入错误，请输入正确的密码");
            mv = new ModelAndView("forward:/public/jumpSecretEdit/" + adminUser.getId());
        }
        return mv;
    }

    /**
     * 修改订单设置界面，跳转
     *
     * @param
     * @return
     */
    @RequestMapping("/jumpOrderSetEdit/{id}")
    public ModelAndView jumpOrderInfoEdit(@PathVariable(value = "id") String id) {
        ModelAndView modelAndView = new ModelAndView("public/updateOrderSet");
        Attached attached = attachedService.getAllAttached().get(0);
        modelAndView.addObject("attached", attached);
        return modelAndView;
    }

    /**
     * 保存新密码
     */
    @RequestMapping("/saveOrderSetEdit")
    public ModelAndView saveOrderInfoEdit(Attached attached, HttpServletRequest request)
            throws IllegalStateException, IOException {
        ModelAndView mv = new ModelAndView("pubic/updateOrderSet");
        AttachedExample userEx = new AttachedExample();
        cn.bupt.adt.entity.autogenerate.AttachedExample.Criteria criteria = userEx.createCriteria();
        criteria.andDeductionMoneyEqualTo(attached.getDeductionMoney());
        Boolean flag = attachedService.updateInfo(attached);
        if (flag) {
            request.setAttribute("resultMsg", "修改成功");
            mv = new ModelAndView("forward:/public/jumpOrderSetEdit/" + String.valueOf(attached.getId()));
        } else {
            request.setAttribute("resultMsg", "修改失败请重试");
            mv = new ModelAndView("forward:/public/jumpOrderSetEdit/" + String.valueOf(attached.getId()));
        }
        return mv;
    }

    /**
     * 修改管理员信息界面，跳转
     *
     * @param
     * @return
     */
    @RequestMapping("/jumpInfoEdit/{id}")
    public ModelAndView jumpInfoEdit(@PathVariable(value = "id") int id) {
        ModelAndView modelAndView = new ModelAndView("public/updateInfo");
        AdminUser adminUser = loginServie.getUserById(id);
        modelAndView.addObject("adminUser", adminUser);
        return modelAndView;
    }

    /**
     * 保存新密码
     */
    @RequestMapping("/saveInfoEdit")
    public ModelAndView saveInfoEdit(AdminUserModel adminUser, HttpServletRequest request)
            throws IllegalStateException, IOException {
        ModelAndView mv = new ModelAndView("pubic/updateInfo");
        AdminUserExample userEx = new AdminUserExample();
        cn.bupt.adt.entity.autogenerate.AdminUserExample.Criteria criteria = userEx.createCriteria();
        criteria.andStudioEqualTo(adminUser.getStudio());
        criteria.andPhoneEqualTo(adminUser.getPhone());
        criteria.andNameEqualTo(adminUser.getName());
        Boolean flag = adminUserService.updateInfo(adminUser);
        if (flag) {
            request.setAttribute("resultMsg", "修改成功");
            mv = new ModelAndView("forward:/public/adminUserDetail/" + adminUser.getId());
        } else {
            request.setAttribute("resultMsg", "修改失败请重试");
            mv = new ModelAndView("forward:/public/jumpInfoEdit/" + adminUser.getId());
        }
        return mv;
    }

    //查看管理员信息详情
    @RequestMapping("/adminUserDetail/{id}")
    public ModelAndView AdminUserDetail(@PathVariable("id") int id) {
        ModelAndView mv = new ModelAndView(Constants.AdminUserDetail);
        AdminUser adminUser = loginServie.getUserById(id);
        mv.addObject("adminUser", adminUser);
        return mv;
    }

    @RequestMapping("/logout")
    public ModelAndView logout(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("redirect:public/login");
        request.getSession().removeAttribute(Constants.ADMIN_USER);
        request.getSession().invalidate();
        return mv;
    }
}
